<template>
  <div class="app-wrapper">
    <div class="sidebar-container">
      <file-search v-model="searchTitle" @create="fileCreate" @search="handleSearch" @clear="handleSearch" @keyup.enter.native="handleSearch" />
      <file-list :file-list="fileList" :active-index.sync="activeIndex" @itemClick="handleItemChange" @refresh="getFileList" />
    </div>
    <div class="main-container">
      <file-edit
        v-model="fileItem.content"
        :title.sync="fileItem.title"
        :box-shadow="false"
        :subfield="false"
        :short-cut="false"
        @titleBlur="updateTitle"
        @change="updateContent"
      />
    </div>
  </div>
</template>

<script>
import dayjs from 'dayjs';
import { cloneDeep, debounce } from 'lodash-es';
import FileSearch from '@/components/FileSearch.vue';
import FileList from '@/components/FileList.vue';
import FileEdit from '@/components/FileEdit.vue';

export default {
  name: 'Home',
  components: { FileSearch, FileList, FileEdit },
  data() {
    return {
      searchTitle: '',
      fileList: [],
      activeIndex: 0,
      fileItem: {
        title: '',
        content: '',
      },
    };
  },
  mounted() {
    this.getFileList();
  },
  methods: {
    // 新建文件
    fileCreate() {
      const defaultFile = { title: '无标题笔记', content: '', isTop: false };
      this.$db.markdown.insert(defaultFile).then(async () => {
        this.getFileList();
      });
    },

    // 搜索笔记列表
    handleSearch() {
      const titleReg = new RegExp(`${this.searchTitle}`, 'i');
      this.getFileList({
        title: titleReg,
      });
    },

    // 获取笔记列表
    async getFileList(query) {
      const list = await this.$db.markdown.find(query).sort({
        isTop: -1,
        updatedAt: -1, // 根据修改时间来倒序排列
      });
      for (const item of list) {
        item.createdAt = dayjs(item.createdAt).format('YYYY-MM-DD HH:mm:ss');
        item.updatedAt = dayjs(item.updatedAt).format('YYYY-MM-DD HH:mm:ss');
      }
      this.fileList = list;
      this.activeIndex = 0;
      if (this.fileList.length === 0) {
        // 创建一个默认模板
        this.fileCreate();
      } else {
        const [firstFileItem] = this.fileList;
        this.fileItem = cloneDeep(firstFileItem);
      }
    },

    // 切换笔记
    handleItemChange(index) {
      this.fileItem = cloneDeep(this.fileList[index]);
    },

    // 修改标题保存
    async updateTitle(title) {
      const { _id } = this.fileItem;
      const originalTitle = this.fileList[this.activeIndex].title;
      if (originalTitle === title) return;
      await this.$db.markdown.update(
        { _id, title: { $ne: title } }, // $ne 如果标题是相同的则不修改
        { $set: { title } },
      );
      this.getFileList();
    },

    // 修改内容保存
    updateContent: debounce(async function (content) {
      const { _id } = this.fileItem;
      const originalContent = this.fileList[this.activeIndex].content;
      if (originalContent === content) return;
      await this.$db.markdown.update({ _id }, { $set: { content } });
      this.getFileList();
    }, 800),
  },
};
</script>

<style lang="scss" scoped>
.app-wrapper {
  display: flex;
  .sidebar-container {
    width: 300px;
    height: 100vh;
    border-right: 1px solid #eaeefb;
  }
  .main-container {
    flex: 1;
    overflow: hidden;
  }
}
</style>
